import * as THREE from 'three'
import '../base/index.css'
import { City } from './city'
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js'
export const initCity = () => {
  // 1-获取cavans元素
  const canvas = document.getElementById('webgl')
  // 创建场景
  const scene = new THREE.Scene()
  // 创建相机 角度 宽高比例 near far
  const camera = new THREE.PerspectiveCamera(
    45,
    window.innerWidth / window.innerHeight,
    1,
    100000
  )
  camera.position.set(1000, 500, 100)
  scene.add(camera)
  // 添加轨道控件
  // 由于canvas元素不是webgl生成的 所以需要添加第二个参数
  const controls = new OrbitControls(camera, canvas)
  // 是否有惯性
  controls.enableDamping = true
  // 是否可以缩放
  controls.enableZoom = false
  // 最近 最远距离
  controls.minDistance = 100
  controls.maxDistance = 2000
  // 开启右键拖动
  controls.enablePan = true
  // 添加环境光
  scene.add(new THREE.AmbientLight(0xababab))
  // 添加平行光
  const directionalLight = new THREE.DirectionalLight(0xababab)
  directionalLight.setRotationFromAxisAngle(0, 0, 0)
  scene.add(directionalLight)
  // 创建渲染器
  const renderer = new THREE.WebGLRenderer({
    canvas
  })
  renderer.setSize(window.innerWidth, window.innerHeight)
  // 设置像素 让渲染器和当前浏览器一样的像素比例
  renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2))
  // 设置场景颜色
  renderer.setClearColor(new THREE.Color(0x000000), 1)
  // 城市
  const city = new City(scene, camera, controls)

  const colok = new THREE.Clock()
  const start = () => {
    city.start(colok.getDelta())
    controls.update()
    // 渲染
    renderer.render(scene, camera)
    requestAnimationFrame(start)
  }
  start()

  window.addEventListener('resize', () => {
    // 相机更新宽高比
    camera.aspect = window.innerWidth / window.innerHeight
    // 更新相机的投影矩阵
    camera.updateProjectionMatrix()
    // 设置像素比
    renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2))
  })
}
